package com.nondo.rdp.finance.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import com.nondo.rdp.core.domain.attach.Attach;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.repository.AttachRepository;
import com.nondo.rdp.finance.service.AttachService;

@Transactional
@Service
public class AttachServiceImpl implements AttachService {
    @Autowired
    AttachRepository AttachRepository;

    @Override
    public Attach findOne(Long id) {
        return this.AttachRepository.findOne(id);
    }

    @Override
    public Attach save(Attach Attach) {
        return this.AttachRepository.save(Attach);
    }

    @Override
    public void update(Attach Attach) {
        this.AttachRepository.update(Attach.getPath(), Attach.getRemark(), Attach.getId());
    }
    
    @Override
    public void delete(Long id) {
        this.AttachRepository.deleteById(id);
    }

    @Override
    public Page<Attach> findAll(Page<Attach> page, Attach attach) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Attach> dictPage = AttachRepository.findAll((root, query, builder) -> {
        	List<Predicate> predicates = new ArrayList<>();
        	if (attach != null) {
	            if (StringUtils.isNotEmpty(attach.getRemark())) {
	                predicates.add(builder.like(root.get("title"), "%" + attach.getRemark() + "%"));
	            }
        	}
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_DELETE));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
        	
            return builder.and(predicatesArray);
        	
        }, pageRequest);

        return new Page<Attach>(dictPage);
    }
}